<?php

namespace app\common\model\banxi\grammar;

use app\common\model\common\BaseModel;
use think\model\concern\SoftDelete;

/**
 * 语法年级选择
 */
class GrammarSelectGrade extends BaseModel
{
    use SoftDelete;

    protected $name = 'banxi_grammar_select_grade';

    protected $autoWriteTimestamp = true;

    protected $deleteTime = 'del';

    protected $defaultSoftDelete = 0;

    protected $append = [

    ];

    protected $type = [
        'id' => 'string',
        'del' => 'string',
        'studentId' => 'string',
        'gradeId' => 'string',
        'createTime' => 'timestamp:Y-m-d H:i:s',
        'updateTime' => 'timestamp:Y-m-d H:i:s',
    ];


    //-----------------------------------------------------------------------------------
    //｜                                   获取器                                       ｜
    //-----------------------------------------------------------------------------------


    //-----------------------------------------------------------------------------------
    //｜                                   处理方法                                       ｜
    //-----------------------------------------------------------------------------------


    /**
     * 根据学生ID获取选择的年级记录
     *
     * @param int $studentId 学生ID
     * @return GrammarSelectGrade|null
     */
    public function getByStudentId($studentId)
    {
        return $this->where('studentId', $studentId)
            ->order('id', 'desc')
            ->limit(1)
            ->find();
    }

    /**
     * 切换年级
     *
     * @param int $gradeId 年级ID
     * @param int $studentId 学生ID
     * @return GrammarSelectGrade|bool
     */
    public function switchGrade($gradeId, $studentId)
    {
        // 获取学生当前选择的年级记录
        $selectGradeCurrent = $this->getByStudentId($studentId);

        // 准备数据
        $data = [
            'gradeId' => $gradeId,
            'studentId' => $studentId
        ];

        // 如果已存在记录，则更新；否则创建新记录
        if ($selectGradeCurrent) {
            return $this->update($data, ['id' => $selectGradeCurrent['id']]);
        } else {
            return $this->save($data);
        }
    }

    //-----------------------------------------------------------------------------------
    //｜                                   模型关联                                       ｜
    //-----------------------------------------------------------------------------------

}